package com.ys.service.business.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ys.entity.base.TbSite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.EditDto;
import com.ys.entity.amazonorder.TbBaseinfoDwmc;
import com.ys.entity.amazonorder.TbBaseinfoLmwh;
import com.ys.entity.base.TpAmazonRegionItem;
import com.ys.entity.business.TpBoutique;
import com.ys.entity.business.TpBoutiqueSiteDetail;
import com.ys.entity.sys.YsCol;
import com.ys.mapper.business.TpBoutiqueMapper;
import com.ys.mapper.business.TpBoutiqueSiteDetailMapper;
import com.ys.service.business.TpBoutiqueSiteDetailService;
import com.ys.util.CheckUtil;
import com.ys.vo.R;

import lombok.AllArgsConstructor;
import lombok.Data;


/**
 * 精品库站点信息
 */
@Service("tpBoutiqueSiteDetailService")
public class TpBoutiqueSiteDetailServiceImpl implements TpBoutiqueSiteDetailService {
	private static final Logger logger = LoggerFactory.getLogger(TpBoutiqueSiteDetailServiceImpl.class);

	@Autowired
	private TpBoutiqueMapper tpBoutiqueMapper;

	@Autowired
	private TpBoutiqueSiteDetailMapper tpBoutiqueSiteDetailMapper;

	@Autowired
	private CheckUtil checkUtil;



	/**
	 * 精品库站点信息新增
	 */
	@Override
	public R add(Map<String, Object> params) throws Exception{

		//return R.ok(AddDto.gotoEdit("/web/business/webTpBoutiqueController/toEdit?id=" ));
		return R.ok();
	}

	/**
	 * 精品库站点详情表信息新增,只新增站点信息
	 */
	@Override
	public R toAddOnlySite(Map<String, Object> params) throws Exception{
		logger.info("精品库站点详情表信息新增,只新增站点信息传参："+params);
		TpBoutiqueSiteDetail tpBoutiqueSiteDetail = JSON.parseObject(JSON.toJSONString(params), TpBoutiqueSiteDetail.class);
		tpBoutiqueSiteDetail.setStatus(1);
		tpBoutiqueSiteDetailMapper.insert(tpBoutiqueSiteDetail);
		//List<TpBoutiqueSiteDetail> tpBoutiqueSiteDetailList = new TpBoutiqueSiteDetail().setBoutiqueId(tpBoutiqueSiteDetail.getBoutiqueId()).queryList();
		Map<String, Object> detailParams = new TpBoutiqueSiteDetail()
				/*
				.addField("I.CountryName AS countryName")//站点
				.addField("R.Name AS regionName")//区域
				.addField("R.PlatformCode AS platformCode")//平台
				.addLeftJoin("TP_AmazonRegionItem I ON A.AmazonRegionItemId = I.Id")
				.addLeftJoin("TP_AmazonRegion R ON I.RegionCode = R.Code")
				.addLeftJoin("TB_Platform R1 ON R1.Code = R.PlatformCode")
				 */
		.addLeftJoin("TB_Site S ON S.Id = A.SiteId")
		.addLeftJoin("TP_AmazonRegion B ON B.Code = S.RegionCode")
				.addField("B.Name regionName")
		.addLeftJoin("TB_Platform B1 ON B1.Code = B.PlatformCode")
				.addField("B1.Code platformCode")
                .addField("B1.Name platformName")
		.addLeftJoin("TB_Country C ON C.Id = S.CountryId")
				.addField("C.Name countryName")

				.setId(tpBoutiqueSiteDetail.getId())
				.queryFirstMap();
		TpBoutiqueDetailEdit detail = new TpBoutiqueDetailEdit(detailParams);
		return R.ok(detail);
	}

	@Data
	@AllArgsConstructor
	private static class TpBoutiqueDetailEdit{
		private Map<String, Object> tpBoutiqueSiteDetail;
	}



	/**
	 * 精品库站点信息修改
	 */
	@Override
	public R update(Map<String, Object> params) throws Exception{
		TpBoutiqueSiteDetail tpBoutiqueSiteDetail = JSON.parseObject(JSON.toJSONString(params), TpBoutiqueSiteDetail.class);
		tpBoutiqueSiteDetailMapper.update(tpBoutiqueSiteDetail);
		
		// 通过ID获取当前数据
		TpBoutiqueSiteDetail currentDetail = new TpBoutiqueSiteDetail().setId(tpBoutiqueSiteDetail.getId()).queryFirst();
		/*
		 * 更新封面图信息
		 * 第一条站点信息的主图1，设置为精品库的封面图
		 */
		// 获取第一条站点信息，若第一条和当前条是同一条，则更新封面图
		TpBoutiqueSiteDetail detailFirst = new TpBoutiqueSiteDetail().setBoutiqueId(currentDetail.getBoutiqueId()).setOrderby("A.Id asc").queryFirst();
		String mainPic1 = detailFirst.getMainPic1();
		if (detailFirst.getId().longValue() == currentDetail.getId().longValue() && mainPic1 != null && mainPic1.length() != 0) {
			TpBoutique tpBoutique = new TpBoutique();
			tpBoutique.setId(detailFirst.getBoutiqueId());
			tpBoutique.setCoverImg(mainPic1);
			tpBoutiqueMapper.update(tpBoutique);
		}
		//return R.ok(AddDto.noAction());
		//return R.ok(AddDto.gotoEdit("/web/business/tpBoutiqueSiteDetail/toEdit?id=" + tpBoutiqueSiteDetail.getId()));
		//return R.ok(EditDto.closeTab());
		return R.ok(EditDto.closeAndReload());
	}


	//精品库站点信息删除
	@Override
	public int del(long id) throws Exception{
		tpBoutiqueSiteDetailMapper.deleteTrue(id);
		return 1;
	}


	/**
	 * 参数验证
	 */
	@Override
	public String checkParams(Map<String, Object> params,Long menuId) throws Exception {
		logger.info("参数验证传参："+params);
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.Code NOT IN ('apluesFile','boutiqueId')")
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo DESC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TP_BoutiqueSiteDetail",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);

		return backMsg;
	}


	/**
	 * 批量导入站点信息
	 */
	@Override
	public R importInfo(String rows,Long menuId){
		logger.info("精品库站点详情表导入的数据：\n"+rows);
		try {
			//获取所有的精品库信息
			List<TpBoutique> tpBoutiqueList = new TpBoutique().queryList();
			//获取所有的站点信息
			//List<TpAmazonRegionItem> tpAmazonRegionItemList = new TpAmazonRegionItem().queryList();
			List<Map<String,Object>> tbSiteList = new TbSite()
					.addLeftJoin("TP_AmazonRegion B ON B.Code = A.RegionCode")
					.addField("B.Name regionName")
					.addLeftJoin("TB_Platform B1 ON B1.Code = B.PlatformCode")
					.addField("B1.Code platformCode")
					.addLeftJoin("TB_Country C ON C.Id = A.CountryId")
					.addField("C.Name countryName")
					.queryMap();


			//获取所有的商品类目
			List<TbBaseinfoLmwh> tbBaseinfoLmwhList = new TbBaseinfoLmwh().queryList();
			//获取所有的单位信息
			List<TbBaseinfoDwmc> tbBaseinfoDwmcList = new TbBaseinfoDwmc().queryList();

			//获取详情数据
			JSONArray detailList = JSON.parseArray(rows);
			for(int i=0;i<detailList.size();i++){
				JSONObject info = detailList.getJSONObject(i);
				Map infoMap = JSONObject.parseObject(info.toString(), Map.class);
				//验证导入字段
				String backMsg = "";
				//获取pc字段数据
				List<YsCol> listField = new YsCol()
						.where("A.MenuId = "+menuId)
						.setOrderby("A.SortNo ASC")
						.queryList();
				//验证必填字段的非空；其他字段的长度限制、类型
				backMsg = checkUtil.checkTableColLengthAndDataType(
						"TP_BoutiqueSiteDetail",
						listField,
						infoMap,
						ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1
								&& !"id".equals(ysColItem.getCode()) && !"otherFilePath".equals(ysColItem.getCode())
								&& !"commodityLmId".equals(ysColItem.getCode()) && !"normsUnitId".equals(ysColItem.getCode())
								&& !"weightUnitId".equals(ysColItem.getCode())
				);
				if(backMsg!=null && !"".equals(backMsg)){//若有误，则跳过这条信息
					logger.error("第"+(i+1)+"条数据导入有误：\n"+backMsg);
					return R.error("第"+(i+1)+"条数据导入有误：\n"+backMsg);
					//continue;
				}
				//验证商品编码
				if(info.get("code")==null || "".equals(info.get("code"))){
					logger.error("第"+(i+1)+"条数据商品编码为空");
					return R.error("第"+(i+1)+"条数据商品编码为空");
					//continue;
				}
				List<TpBoutique> tpBoutique = tpBoutiqueList.stream().filter(item->item.getCode().equals(info.get("code").toString())).collect(Collectors.toList());
				if(tpBoutique.size()<=0){
					logger.error("第"+(i+1)+"条数据商品编码有误");
					return R.error("第"+(i+1)+"条数据商品编码有误");
					//continue;
				}
				infoMap.put("boutiqueId",tpBoutique.get(0).getId());

				//验证站点信息
				List<Map<String,Object>> tbSiteListByImport = tbSiteList.stream()
						.filter(
								item->item.get("countryName").toString().equals(info.get("countryName").toString())
								&& item.get("regionName").toString().equals(info.get("regionName").toString())
								&& item.get("platformCode").toString().equals(info.get("platform").toString())
						)
						.collect(Collectors.toList());
				if(tbSiteListByImport.size()<=0){
					logger.error("第"+(i+1)+"条数据站点信息有误");
					return R.error("第"+(i+1)+"条数据站点信息有误");
					//continue;
				}
				infoMap.put("siteId",tbSiteListByImport.get(0).get("id"));

				//验证商品类目
				List<TbBaseinfoLmwh> tbBaseinfoLmwh = tbBaseinfoLmwhList.stream().filter(item->item.getName().equals(info.get("baseinfoLmName").toString())).collect(Collectors.toList());
				if(tbBaseinfoLmwh.size()<=0){
					logger.error("第"+(i+1)+"条数据商品类目信息有误");
					return R.error("第"+(i+1)+"条数据商品类目信息有误");
					//continue;
				}
				infoMap.put("commodityLmId",tbBaseinfoLmwh.get(0).getId());

				//验证规格单位
				List<TbBaseinfoDwmc> normsUnitInfo = tbBaseinfoDwmcList.stream().filter(item->item.getNameUnitCn().equals(info.get("normsUnit").toString())).collect(Collectors.toList());
				if(normsUnitInfo.size()<=0){
					logger.error("第"+(i+1)+"条数据规格单位信息有误");
					return R.error("第"+(i+1)+"条数据规格单位信息有误");
					//continue;
				}
				infoMap.put("normsUnitId",normsUnitInfo.get(0).getId());

				//验证重量单位
				List<TbBaseinfoDwmc> weightUnitInfo =  tbBaseinfoDwmcList.stream().filter(item->item.getNameUnitCn().equals(info.get("weightUnit").toString())).collect(Collectors.toList());
				if(weightUnitInfo.size()<=0){
					logger.error("第"+(i+1)+"条数据重量单位信息有误");
					return R.error("第"+(i+1)+"条数据重量单位信息有误");
					//continue;
				}
				infoMap.put("weightUnitId",weightUnitInfo.get(0).getId());

				//新增或编辑
				TpBoutiqueSiteDetail tpBoutiqueSiteDetail = JSON.parseObject(JSON.toJSONString(infoMap), TpBoutiqueSiteDetail.class);
				TpBoutiqueSiteDetail hasDetail = new TpBoutiqueSiteDetail()
						.setBoutiqueId(tpBoutiqueSiteDetail.getBoutiqueId())
						.setSiteId(tpBoutiqueSiteDetail.getSiteId())
						.queryFirst();
				logger.info("导入数据：\n"+infoMap);
				if(hasDetail!=null){//编辑
					tpBoutiqueSiteDetail.setId(hasDetail.getId());
					tpBoutiqueSiteDetailMapper.update(tpBoutiqueSiteDetail);
				}else {//新增
					tpBoutiqueSiteDetailMapper.insert(tpBoutiqueSiteDetail);
				}
			}

		}catch (Exception e){
			logger.error("导入出错：",e.getMessage(),e);
			return R.error("导入出错,请稍后重试!");
		}


		return R.ok("导入成功！");
	}




}
